<template>
  <div class="achievements-container">
    <div class="header">
      <h2>成果管理</h2>
    </div>

    <el-card>
      <el-form :inline="true" class="filter-form">
        <el-form-item label="学生">
          <el-select v-model="filters.studentId" placeholder="所有学生" clearable>
            <el-option v-for="student in students" :key="student.id" :label="student.realName" :value="student.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="filters.type" placeholder="全部类型" clearable>
            <el-option label="论文" value="论文" />
            <el-option label="专利" value="专利" />
            <el-option label="项目" value="项目" />
            <el-option label="获奖" value="获奖" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="全部状态" clearable>
            <el-option label="待审核" value="待审核" />
            <el-option label="已通过" value="已通过" />
            <el-option label="已拒绝" value="已拒绝" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="filterAchievements">筛选</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="achievements" style="width: 100%">
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="type" label="类型" width="100" />
        <el-table-column label="学生" width="120">
          <template #default="scope">
            {{ scope.row.student ? scope.row.student.realName : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="提交时间" width="180" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button link type="primary" @click="viewAchievement(scope.row)">查看</el-button>
            <el-button 
              link 
              type="primary" 
              :disabled="scope.row.status !== '待审核'" 
              @click="reviewAchievement(scope.row)">审核</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看成果对话框 -->
    <el-dialog v-model="showViewDialog" title="成果详情" width="50%">
      <div class="achievement-detail" v-if="currentAchievement">
        <div class="detail-item">
          <span class="label">标题：</span>
          <span class="value">{{ currentAchievement.title }}</span>
        </div>
        <div class="detail-item">
          <span class="label">类型：</span>
          <span class="value">{{ currentAchievement.type }}</span>
        </div>
        <div class="detail-item">
          <span class="label">学生：</span>
          <span class="value">{{ currentAchievement.student ? currentAchievement.student.realName : '' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">提交时间：</span>
          <span class="value">{{ currentAchievement.createdAt }}</span>
        </div>
        <div class="detail-item">
          <span class="label">状态：</span>
          <span class="value">
            <el-tag :type="getStatusType(currentAchievement.status)">{{ currentAchievement.status }}</el-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="label">描述：</span>
          <p class="value description">{{ currentAchievement.description }}</p>
        </div>
        <div class="detail-item" v-if="currentAchievement.comments">
          <span class="label">审核反馈：</span>
          <p class="value feedback">{{ currentAchievement.comments }}</p>
        </div>
        <div class="detail-item" v-if="currentAchievement.attachmentUrl">
          <span class="label">附件：</span>
          <div class="value">
            <el-button type="primary" link>下载附件</el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="showReviewDialog" title="审核成果" width="50%">
      <div class="review-form" v-if="currentAchievement">
        <div class="detail-item">
          <span class="label">标题：</span>
          <span class="value">{{ currentAchievement.title }}</span>
        </div>
        <div class="detail-item">
          <span class="label">学生：</span>
          <span class="value">{{ currentAchievement.student ? currentAchievement.student.realName : '' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">类型：</span>
          <span class="value">{{ currentAchievement.type }}</span>
        </div>
        <div class="detail-item">
          <span class="label">描述：</span>
          <p class="value description">{{ currentAchievement.description }}</p>
        </div>
        <div class="detail-item" v-if="currentAchievement.attachmentUrl">
          <span class="label">附件：</span>
          <div class="value">
            <el-button type="primary" link>下载附件</el-button>
          </div>
        </div>
        <el-form :model="reviewForm" label-width="120px" class="review-form">
          <el-form-item label="审核结果" prop="result">
            <el-radio-group v-model="reviewForm.result">
              <el-radio label="approve">通过</el-radio>
              <el-radio label="reject">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="反馈意见" prop="feedback">
            <el-input 
              v-model="reviewForm.feedback" 
              type="textarea" 
              rows="4" 
              placeholder="请输入审核反馈意见"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showReviewDialog = false">取消</el-button>
          <el-button type="primary" @click="submitReview" :loading="submitting">提交审核</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import TeacherService from '@/api/teacher'

interface Student {
  id: number
  username: string
  realName: string
}

interface Achievement {
  id: number
  title: string
  type: string
  description: string
  student: {
    id: number
    username: string
    realName: string
  }
  createdAt: string
  status: string
  comments?: string
  attachmentUrl?: string
}

export default defineComponent({
  name: 'TeacherAchievements',
  setup() {
    const loading = ref(true)
    const submitting = ref(false)
    const achievements = ref<Achievement[]>([])
    const students = ref<Student[]>([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const showViewDialog = ref(false)
    const showReviewDialog = ref(false)
    const currentAchievement = ref<Achievement | null>(null)

    const filters = reactive({
      studentId: '',
      type: '',
      status: ''
    })

    const reviewForm = reactive({
      result: 'approve',
      feedback: ''
    })

    const getStatusType = (status: string) => {
      switch (status) {
        case '待审核':
          return 'info'
        case '已通过':
          return 'success'
        case '已拒绝':
          return 'danger'
        default:
          return ''
      }
    }

    const fetchStudents = async () => {
      try {
        const response = await TeacherService.getMyStudents()
        students.value = response.data
      } catch (error) {
        console.error('获取学生列表失败:', error)
        ElMessage.error('获取学生列表失败')
      }
    }

    const fetchAchievements = async () => {
      loading.value = true
      try {
        // 根据筛选条件获取不同状态的成果
        let response
        if (filters.status === '待审核') {
          response = await TeacherService.getPendingAchievements()
        } else {
          response = await TeacherService.getReviewedAchievements()
        }
        
        // 过滤数据
        let filteredData = response.data
        
        if (filters.studentId) {
          filteredData = filteredData.filter((item: Achievement) => 
            item.student && item.student.id === parseInt(filters.studentId))
        }
        
        if (filters.type) {
          filteredData = filteredData.filter((item: Achievement) => 
            item.type === filters.type)
        }
        
        achievements.value = filteredData
        total.value = filteredData.length
      } catch (error) {
        console.error('获取成果列表失败:', error)
        ElMessage.error('获取成果列表失败')
      } finally {
        loading.value = false
      }
    }

    const filterAchievements = () => {
      fetchAchievements()
    }

    const resetFilters = () => {
      filters.studentId = ''
      filters.type = ''
      filters.status = ''
      fetchAchievements()
    }

    const handleSizeChange = (val: number) => {
      pageSize.value = val
      fetchAchievements()
    }

    const handleCurrentChange = (val: number) => {
      currentPage.value = val
      fetchAchievements()
    }

    const viewAchievement = async (achievement: Achievement) => {
      try {
        // 获取完整的成果详情
        const response = await TeacherService.getAchievementById(achievement.id)
        currentAchievement.value = response.data
        showViewDialog.value = true
      } catch (error) {
        console.error('获取成果详情失败:', error)
        ElMessage.error('获取成果详情失败')
      }
    }

    const reviewAchievement = (achievement: Achievement) => {
      currentAchievement.value = achievement
      reviewForm.result = 'approve'
      reviewForm.feedback = ''
      showReviewDialog.value = true
    }

    const submitReview = async () => {
      if (!currentAchievement.value) return
      
      submitting.value = true
      try {
        const status = reviewForm.result === 'approve' ? '已通过' : '已拒绝'
        
        // 调用API提交审核结果
        await TeacherService.reviewAchievement({
          achievementId: currentAchievement.value.id,
          status: status,
          comments: reviewForm.feedback
        })
        
        ElMessage({
          type: 'success',
          message: `成果已${status}`
        })
        
        showReviewDialog.value = false
        // 重新获取成果列表，确保显示最新状态
        fetchAchievements()
      } catch (error) {
        console.error('提交审核失败:', error)
        ElMessage.error('提交审核失败')
      } finally {
        submitting.value = false
      }
    }

    onMounted(() => {
      fetchStudents()
      fetchAchievements()
    })

    return {
      loading,
      submitting,
      achievements,
      students,
      total,
      currentPage,
      pageSize,
      filters,
      showViewDialog,
      showReviewDialog,
      currentAchievement,
      reviewForm,
      getStatusType,
      filterAchievements,
      resetFilters,
      handleSizeChange,
      handleCurrentChange,
      viewAchievement,
      reviewAchievement,
      submitReview
    }
  }
})
</script>

<style scoped>
.achievements-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.filter-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.achievement-detail, .review-form {
  padding: 10px;
}

.detail-item {
  margin-bottom: 15px;
}

.label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
}

.description, .feedback {
  white-space: pre-line;
  line-height: 1.6;
  margin-top: 5px;
  color: #606266;
}

.feedback {
  color: #67c23a;
}

.review-form {
  margin-top: 20px;
}
</style> 